#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 获取当前脚本文件所在目录的父目录，并构建相对路径
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(current_dir, '..')
sys.path.append(project_path)
sys.path.append(current_dir)
import gpLog
import datetime
import time
import paho.mqtt.client as mqtt
import threading

class GpMqtt:
    def __init__(self, ip, port, user, password):
        self.mqtt_ip = ip
        self.mqtt_port = port
        self.mqtt_username = user
        self.mqtt_password = password
        self.client = None
        self.heartbeat_topic = None
        self.heartbeat_loop_in_secs = 3
        self.task_heartbeat = None
        self.heart_beat_cnts = 0

    def connect(self, on_connect=None, on_message=None, machine_id=None):
        # 创建 MQTT 客户端
        if machine_id is None:
            client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id=None, clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")
        else:
            client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id=f'KDE_MQTT_CFG_CLIENT_ID-{machine_id}', clean_session=True, userdata=None, protocol=mqtt.MQTTv311, transport="tcp")
        # 设置用户名和密码
        if self.mqtt_username is not None:
            client.username_pw_set(self.mqtt_username, self.mqtt_password)
        if on_connect is not None:
            client.on_connect = on_connect
        if on_message is not None:
            client.on_message = on_message
        # 连接到 MQTT 服务器
        client.connect(self.mqtt_ip, self.mqtt_port, 60)
        self.client = client
        self.heartbeatThreadRun = False
        self.task_thread = None

    def periodic_task(self):
        while self.heartbeatThreadRun:
            if(self.client is not None) and (self.heartbeat_topic is not None):
                self.client.publish(self.heartbeat_topic, str(self.heart_beat_cnts))
                self.heart_beat_cnts+=1
            if(self.heartbeat_loop_in_secs<1): 
                self.heartbeat_loop_in_secs= 1
            time.sleep(self.heartbeat_loop_in_secs)

    def start_heartbeat(self, topic_of_heart_beat, loop_in_secs):
        self.heartbeat_topic = topic_of_heart_beat
        self.heartbeatLoop_in_secs = loop_in_secs
        if not self.heartbeatThreadRun:
            self.heartbeatThreadRun = True
            self.task_thread = threading.Thread(target=self.periodic_task)
            self.task_thread.start()

    def post_message(self, topic, payload):
        self.client.publish(topic, payload)

    def stop_heartbeat(self):
        if self.heartbeatThreadRun:
            self.heartbeatThreadRun = False
            if self.task_thread:
                self.task_thread.join()